//
//  PostsHeaderView.m
//  JiaoX
//
//  Created by yinqy on 15/2/28.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "PostsHeaderView.h"
#import "LeftLineView.h"
#import "JXComtPopMenu.h"
#import "LeftLineView.h"
#import "JXUserInfoCtl.h"
#import "JXProdDetailCtl.h"
#import "JXMinePostsCtl.h"
#import "JXPostsListCtl.h"

#define HEADIMG_WIDTH [DimensUtils getScaleX:40]
#define NAMELABEL_FONT_SIZE [DimensUtils getScaleX:14]
#define POSTSTITLE_FONT_SIZE [DimensUtils getScaleX:14]
#define TIMELABEL_FONT_SIZE [DimensUtils getScaleX:12]


@interface PostsHeaderView()<UIWebViewDelegate,JXComtPopMenuDelegate>
{
    UIImageView *_headImg;
    UILabel *_namelabel;
    UIImageView *_genderImg;
    UIButton *_btnTime;
    UIButton *_replyBtn;
    LeftLineView *_postsTitle;
    UIWebView *_webViewContent;
    LeftLineView *_replyTitle;
    UIView *_bottomSplite;
    JXComtPopMenu *menu;
    
    NSString *_userId;
    NSString *_modleId;
    
    UIView *_splite;
    
    UIButton *_goBtn;
    
    NSString *_url;
    
}
@end
@implementation PostsHeaderView

- (instancetype)initWithBBSPosts:(BBSPosts *)posts
{
    self = [super init];
    if (self) {
        //头像
        _headImg = [[UIImageView alloc]init];
        [_headImg setFrame:CGRectMake(10, 15, HEADIMG_WIDTH, HEADIMG_WIDTH)];
        [_headImg.layer setCornerRadius:HEADIMG_WIDTH/2];
        [_headImg.layer setMasksToBounds:YES];
        [self addSubview:_headImg];
        
        //名称
        _namelabel = [[UILabel alloc]init];
        [_namelabel setText:posts.nickName];
        [_namelabel setFont:[UIFont systemFontOfSize:NAMELABEL_FONT_SIZE]];
        [_namelabel setTextColor:JXColor(51, 51, 51)];
        [_namelabel setX:CGRectGetMaxX(_headImg.frame)+5];
        [_namelabel setY:_headImg.y];
        [_namelabel setSize:[_namelabel.text sizeWithFont:_namelabel.font]];
        [_namelabel setHeight:_namelabel.font.lineHeight];
        [self addSubview:_namelabel];
        
        //性别
        _genderImg = [[UIImageView alloc]init];
        [self addSubview:_genderImg];
        
        //分割线
        UIView *splite = [[UIView alloc]init];
        [splite setBackgroundColor:JXColor(204, 204, 204)];
        [splite setFrame:CGRectMake(10, CGRectGetMaxY(_headImg.frame)+15, JXScreenW-10, 0.5)];
        [self addSubview:splite];
        _splite = splite;
        
        //回复按钮
        UIImage *replyImage = [UIImage imageNamed:@"ic_comt_reply"];
        _replyBtn = [[UIButton alloc]init];
        [_replyBtn setImage:replyImage forState:UIControlStateNormal];
        [_replyBtn setImage:[UIImage imageNamed:@"ic_comt_reply_heighlight"] forState:UIControlStateSelected];
        [_replyBtn setImage:[UIImage imageNamed:@"ic_comt_reply_heighlight"] forState:UIControlStateHighlighted];
        [_replyBtn setSize:replyImage.size];
        [_replyBtn setX:JXScreenW-10-_replyBtn.width];[_replyBtn setY:(CGRectGetMinY(splite.frame)-_replyBtn.height)/2];
        [self addSubview:_replyBtn];
        
        //时间
        _btnTime = [[UIButton alloc]init];
        [_btnTime.titleLabel setFont:[UIFont systemFontOfSize:TIMELABEL_FONT_SIZE]];
        [_btnTime setTitleColor:JXColor(102, 102, 102) forState:UIControlStateNormal];
        [_btnTime setImage:[UIImage imageNamed:@"ic_time"] forState:UIControlStateNormal];
        [_btnTime setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        [_btnTime setTitle:@"加载中..." forState:UIControlStateNormal];
        [_btnTime setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_btnTime setFrame:CGRectMake(_namelabel.x, CGRectGetMaxY(_namelabel.frame)+10, CGRectGetMinX(_replyBtn.frame)-_namelabel.x, _btnTime.titleLabel.font.lineHeight)];
        [self addSubview:_btnTime];
        
        //标题
        _postsTitle = [[LeftLineView alloc]initWithTitleFontSize:POSTSTITLE_FONT_SIZE];
        [_postsTitle setX:10];[_postsTitle setY:CGRectGetMaxY(splite.frame)+15];
        [_postsTitle setText:posts.title constrainedToSize:CGSizeMake(JXScreenW-20, MAXFLOAT)];
        [self addSubview:_postsTitle];
        
        _webViewContent = [[UIWebView alloc]init];
        [_webViewContent setFrame:CGRectMake(0, CGRectGetMaxY(_postsTitle.frame)+10, JXScreenW, 300)];
        [_webViewContent setDelegate:self];
        [_webViewContent setUserInteractionEnabled:NO];
        [self addSubview:_webViewContent];
        
        _goBtn = [[UIButton alloc]init];
        [_goBtn setTitle:@"去查看这货" forState:UIControlStateNormal];
        [_goBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_goBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_goBtn setContentMode:UIViewContentModeCenter];
        [_goBtn setSize:CGSizeMake(JXScreenW-JXPublicInset*2, 46.5)];
        [_goBtn setX:10];
        [_goBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
        [_goBtn setHidden:YES];
        [self addSubview:_goBtn];
        
        _replyTitle = [[LeftLineView alloc]initWithTitleFontSize:[DimensUtils getScaleX:14]];
        [_replyTitle setX:10];[_replyTitle setY:CGRectGetMaxY(_webViewContent.frame)+15];
        [_replyTitle setText:@"回帖"];
        [self addSubview:_replyTitle];
        
        
        //底部分割线
//        _bottomSplite = [[UIView alloc]init];
//        [_bottomSplite setBackgroundColor:JXColor(204, 204, 204)];
//        [_bottomSplite setFrame:CGRectMake(10, CGRectGetMaxY(_webViewContent.frame)+15, JXScreenW-10, 0.5)];
//        [self addSubview:_bottomSplite];
        
        [self setFrame:CGRectMake(0, 0, JXScreenW, CGRectGetMaxY(_replyTitle.frame))];
        
        
        
        
        [self addKVO];
    }
    return self;
}

-(UIView *)getHeaderViewWithTitle:(NSString *)title{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, SCALEX(32))];
    [view setBackgroundColor:JXColor(238, 238, 238)];
    
    UILabel *titlelabel = [[UILabel alloc]init];
    [titlelabel setText:title];
    [titlelabel setTextColor:JXColor(102, 102, 102)];
    [titlelabel setX:10];
    [titlelabel setFont:SYS_FONT(SCALEX(12))];
    [titlelabel setHeight:view.height];
    [titlelabel setWidth:[titlelabel.text sizeWithFont:titlelabel.font].width];
    [view addSubview:titlelabel];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:IMG(@"self_item_arrow")];
    [imageView setCenterY:titlelabel.centerY];
    [imageView setX:view.width-imageView.width-10];
    [view addSubview:imageView];
    
    [view setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerViewClick:)];
    [view addGestureRecognizer:tap];
    return view;
}

-(void)headerViewClick:(UITapGestureRecognizer *)ges{
    JXPostsListCtl *ctl = [[JXPostsListCtl alloc]initWithModelId:_modleId];
    [self.viewController.navigationController pushViewController:ctl animated:YES];
}

-(void)setPostsInfo:(PostsDetailsResult *)result{
    [_webViewContent loadHTMLString:result.posts.content baseURL:nil];
    _modleId = [NSString stringWithFormat:@"%ld",(long)result.posts.modelId];
    CGFloat insetY = 0;
    if (!ISBLANK(result.posts.modelName)) {
        //代表显示headerView
        UIView *view = [self getHeaderViewWithTitle:[NSString stringWithFormat:@"来自\"%@\"",result.posts.modelName]];
        [self addSubview:view];
        insetY = CGRectGetMaxY(view.frame);
    }
    
    if (insetY>0) {
        [_headImg setY:insetY+15];
        [_namelabel setY:_headImg.y];
        [_replyBtn setCenterY:_headImg.centerY];
        [_btnTime setY:CGRectGetMaxY(_namelabel.frame)+10];
        [_splite setY:CGRectGetMaxY(_headImg.frame)+15];
        [_postsTitle setY:CGRectGetMaxY(_splite.frame)+15];
        [_webViewContent setY:CGRectGetMaxY(_postsTitle.frame)+10];
    }
    
    //1.设置头像
    [_headImg sd_setImageWithURL:[NSURL URLWithString:result.userInfo.userImg]];
    //2.设置名称
    [_namelabel setText:result.userInfo.nickName];
    [_namelabel setSize:[_namelabel.text sizeWithFont:_namelabel.font]];
    //3.设置性别
    //默认为未知性别
    NSString *genderImg = @"ic_gender_unknow";
    //判断是男是女
    if ([[NSString stringWithFormat:@"%@",result.userInfo.userGender] isEqualToString:@"1"]) {
        genderImg = @"ic_gender_man";
    }else if([[NSString stringWithFormat:@"%@",result.userInfo.userGender] isEqualToString:@"2"]){
        genderImg = @"ic_gender_woman";
    }
    //判断是否是vip
    if (result.userInfo.level) {
        genderImg = [NSString stringWithFormat:@"%@_vip",genderImg];
    }
    [_genderImg setImage:[UIImage imageNamed:genderImg]];
    [_genderImg setSize:_genderImg.image.size];
    [_genderImg setX:CGRectGetMaxX(_namelabel.frame)+2.5];
    [_genderImg setY:_namelabel.centerY-_genderImg.height/2];
    
    [_replyBtn addTarget:self action:@selector(replyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //4.设置时间
    [_btnTime setTitle:result.posts.createTime forState:UIControlStateNormal];
    [_btnTime setY:CGRectGetMaxY(_namelabel.frame)+10];
    
    //5.设置标题
    [_postsTitle setText:result.posts.title constrainedToSize:CGSizeMake(JXScreenW-20, MAXFLOAT)];
    
    //6.设置webview位置
    [_webViewContent setX:0];
    [_webViewContent setHeight:300];
    [_webViewContent setY:CGRectGetMaxY(_postsTitle.frame)+10];
    
    [self setFrame:CGRectMake(0, 0, JXScreenW, CGRectGetMaxY(_webViewContent.frame))];
    
    if (!ISBLANK(result.posts.urlValue)) {
        [_goBtn addTarget:self action:@selector(goBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _url = result.posts.urlValue;
    }
    
    _userId = result.userInfo.userId;
    _headImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerImgClick:)];
    [_headImg addGestureRecognizer:tap];

}

-(void)headerImgClick:(UITapGestureRecognizer *)ges{
    if ([[NSString stringWithFormat:@"%@",_userId] isEqualToString:CURRENTUSERID]) {
        JXMinePostsCtl *ctl = [[JXMinePostsCtl alloc]initWithModelList:nil];
        [self.viewController.navigationController pushViewController:ctl animated:YES];
    }else{
        JXUserInfoCtl *ctl = [[JXUserInfoCtl alloc]initWithUserId:_userId];
        [self.viewController.navigationController pushViewController:ctl animated:YES];
    }
}

-(void)replyBtnClick:(UIButton *)btn{
    menu = [[JXComtPopMenu alloc]initHaveArrow:NO];
    [menu setTag:-1];//设置tag为负1，代表用户点击的是楼主的回复
    menu.delegate = self;
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    CGRect rect=[btn convertRect:btn.bounds toView:window];
    [menu showInPoint:CGPointMake(CGRectGetMinX(rect)-menu.container.width-5, rect.origin.y+rect.size.height*0.5-menu.container.height*0.5)];
    [btn setSelected:YES];
}

/**
 *  添加webview的内容高度改变监听
 */
-(void)addKVO{
    UIScrollView *scrollview = [[_webViewContent subviews]firstObject];
    [scrollview addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"contentSize"])
    {
        NSValue *oldSize = [change objectForKey:@"old"];
        NSValue *newSize = [change objectForKey:@"new"];
        if ([oldSize CGSizeValue].height!=[newSize CGSizeValue].height) {
            [self webViewDidFinishLoad:_webViewContent];
        }
    }
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    CGRect newFrame = webView.frame;
    newFrame.size.height = actualSize.height;
    webView.frame = newFrame;
    
    if (!ISBLANK(_url)) {
        [_goBtn setHidden:NO];
        
        [_goBtn setY:CGRectGetMaxY(webView.frame)+5];
        [_replyTitle setY:CGRectGetMaxY(_goBtn.frame)+15];
    }else{
        [_replyTitle setY:CGRectGetMaxY(webView.frame)+15];
    }
    
    [self setFrame:CGRectMake(0, 0, JXScreenW, CGRectGetMaxY(_replyTitle.frame))];
    if ([self.delegate respondsToSelector:@selector(webviewLoadFinish)]) {
        [_delegate webviewLoadFinish];
    }
}

#pragma mark comtMenuDelegate
-(void)popMenuDidDismissed:(JXComtPopMenu *)popMenu{
    [_replyBtn setSelected:NO];
}

-(void)popMenuReplyBtnClick:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(replyBtnClick:)]) {
        [_delegate replyBtnClick:btn];
    }
}


-(void)popMenuChatBtnClick:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(chatBtnClick:)]) {
        [_delegate chatBtnClick:btn];
    }
}

-(void)goBtnClick:(UIButton *)btn{
    if (_url) {
        JXProdDetailCtl *ctl = [[JXProdDetailCtl alloc]initWithPordId:_url];
        [self.viewController.navigationController pushViewController:ctl animated:YES];
    }
}

-(void)dealloc{
    UIScrollView *scrollview = [[_webViewContent subviews]firstObject];
    [scrollview removeObserver:self forKeyPath:@"contentSize"];
}

@end
